/**
 * yeahmobi.com Inc.
 * Copyright © 2014 YeahMobi | All Rights Reserved.
 */

package com.ndp.fb.util;

import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.model.business.bo.nfs.NfsConfig;
import com.ndpmedia.fb.pmd.nfs.Client;
import com.ndpmedia.fb.pmd.nfs.ClientService;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Title: NFSUtil.java
 * @Copyright: Copyright © 2015
 * @Description:
 * @Company: yeahmobi
 * @Created on 上午11:50:01
 * @author giser.yang
 */
@Component
public class NFSUtil {
	private static Logger logger = LoggerFactory.getLogger(NFSUtil.class);
	@Autowired
	private NfsConfig nfsConfig;
	private static char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
			'f' };

	/**
	 * 上传文件到NFS并返回NFS文件名
	 *
	 *            源文件地址
	 * @param isThumbnail
	 *            是否修改为缩略图
	 * @return NFS文件名
	 */
	public String uploadToNFS(String url, boolean isThumbnail) {
		String nfsFileName = null;
		URLConnection urlConnection = null;
		InputStream inputStream = null;
		Client client = null;
		File litImage = new File(com.ndp.fb.util.UUID.get() + ".jpg");
		try {
			client = new ClientService(nfsConfig.getServerIp(), nfsConfig.getServerPort(), nfsConfig.getCharset());
			URL httpUrl = new URL(url);
			urlConnection = httpUrl.openConnection();
			urlConnection.setConnectTimeout(CommonConstants.HTTP_CONNECTION_TIME_OUT);
			urlConnection.setReadTimeout(CommonConstants.HTTP_READ_TIME_OUT);
			inputStream = urlConnection.getInputStream();
			if (isThumbnail) {
				Thumbnails.of(inputStream).forceSize(156, 109).outputQuality(0.5).toFile(litImage);
				nfsFileName = client.uploadFile(litImage);
			} else {
				byte[] bytes = ArrayUtil.input2byte(inputStream);
				nfsFileName = client.uploadFile(bytes, com.ndp.fb.util.UUID.get() + ".jpg");
			}
		} catch (Exception e) {
			logger.error("上传文件到NFS出现异常>>>，url:{}",url);
			logger.error(e.getMessage(), e);
		} finally {
			if (null != inputStream) {
				IOUtils.closeQuietly(inputStream);
			}
			if (null != urlConnection) {
				IOUtils.close(urlConnection);
			}
			if (null != client) {
				IOUtils.closeQuietly(client);
			}
			if (litImage != null) {
				litImage.delete();
			}
			if (client != null) {
				try {
					client.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
		return nfsFileName;
	}



	public byte[] downNfsFile(String fileId) {
		byte[] bytes = null;
		ClientService client = null;
		try {
			client = new ClientService(nfsConfig.getServerIp(), nfsConfig.getServerPort(), nfsConfig.getCharset());
			bytes = client.download(fileId);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (client != null) {
				client.close();
			}
		}

		return bytes;
	}

	public String getFileMd5(String fileId) {
		try {
			byte[] file = this.downNfsFile(fileId);
			return FileUtil.getFileMd5(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String uploadNfsFile(File file) throws Exception{
		String nfsId = null;
		ClientService clientService = null;
		try{
			clientService = new ClientService(nfsConfig.getServerIp(), nfsConfig.getServerPort(), nfsConfig.getCharset());
			nfsId = clientService.uploadFile(file);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			//是否抛出异常？
		   throw e;
		} finally {
			if (null != clientService) {
				clientService.close();
			}
		}

		return nfsId;
	}
}
